package worker

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

//命令行服务

var (
	CmdlineBinds = make(map[string]func()) //处理列表
	CmdlineChan  = make(chan string, 16)   //队列
)

// CmdlineWorker
// @Description: 命令行
type CmdlineWorker struct {
}

// NewCmdlineWorker 创建
// @return *CmdlineWorker
func NewCmdlineWorker() *CmdlineWorker {
	s := &CmdlineWorker{}
	return s
}

// Start 启动
// @receiver w
// @param fnRegister
func (w *CmdlineWorker) Start(fnRegister func()) {
	fnRegister()
	for {
		f := bufio.NewReader(os.Stdin) //读取输入的内容
		var msg string
		msg, _ = f.ReadString('\n') //定义一行输入的内容分隔符。
		msg = strings.ReplaceAll(msg, "\r\n", "")
		if len(msg) > 0 && len(msg) < 100 {
			CmdlineChan <- msg
		}
	}
}

// CmdlineWorkerAddCmd 外部添加指令
// @param cmd
func CmdlineWorkerAddCmd(cmd string) {
	CmdlineChan <- cmd
}

// CmdlineWorkerBind 绑定
// @param cmd
// @param fn
func CmdlineWorkerBind(cmd string, fn func()) {
	CmdlineBinds[cmd] = fn
}

// CmdlineWorkerBinds
// @Description:
// @param cmds
// @param fn
func CmdlineWorkerBinds(cmds []string, fn func()) {
	for _, v := range cmds {
		CmdlineWorkerBind(v, fn)
	}
}

// CmdlineExec
// @Description:
// @param cmd
func CmdlineExec(cmd string) {
	fn, ok := CmdlineBinds[cmd]
	if ok {
		fn()
	} else {
		fmt.Println("无效指令：", cmd)
	}
}
